package org.jeecg.modules.wx.service;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jeecg.dingtalk.api.user.JdtUserAPI;
import com.jeecg.qywx.api.user.JwUserAPI;
import com.jeecg.qywx.api.user.vo.User;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.RandomStringUtils;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.FillRuleUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.base.service.BaseCommonService;
import org.jeecg.modules.recharge.entity.Balance;
import org.jeecg.modules.recharge.service.IBalanceService;
import org.jeecg.modules.system.entity.SysThirdAccount;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.mapper.SysUserMapper;
import org.jeecg.modules.system.model.ThirdLoginModel;
import org.jeecg.modules.system.service.ISysThirdAccountService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;

/**
 * @ProjectName: study-room-vue
 * @Author: WenZhengcheng
 * @Date: 2022-5-9 下午 06:44
 * @Desc:
 */

@Slf4j
@Service
@RequiredArgsConstructor
public class WxLoginService {

    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private IBalanceService balanceService;
    @Autowired
    private ISysThirdAccountService sysThirdAccountService;

    @Value("${miniapp.birthday}")
    private String birthday;

    public SysUser wxLogin( String openid) throws WxErrorException {

        // 判断第三方用户表有没有这个人
        LambdaQueryWrapper<SysThirdAccount> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysThirdAccount::getThirdUserUuid, openid);
        SysThirdAccount thirdAccount = sysThirdAccountService.getOne(queryWrapper);
        if (thirdAccount == null) {
            thirdAccount = new SysThirdAccount();
            thirdAccount.setStatus(1);
            thirdAccount.setDelFlag(0);
            thirdAccount.setThirdUserUuid(openid);
            thirdAccount.setThirdUserId(openid);
            thirdAccount.setBirthday(birthday);
            thirdAccount.setRealname("微信用户"+ RandomStringUtils.random(5, false, true));
            thirdAccount.setAvatar("https://cdn.uviewui.com/uview/album/1.jpg");
            sysThirdAccountService.save(thirdAccount);
        }
        SysUser sysUser = this.getSysUserByThird(thirdAccount);
        Balance balance = balanceService.getOne(new LambdaQueryWrapper<Balance>().eq(Balance::getSysUserId,sysUser.getId()));
        if (balance == null) {
            balance = new Balance();
            balance.setBalance(new BigDecimal(0));
            balance.setSysUserId(sysUser.getId());
            balance.setCardNo("" + FillRuleUtil.executeRule("cardno_rule", new JSONObject()));
            balanceService.save(balance);
        }
        return sysUser;
    }

    public SysUser getSysUserByThird(SysThirdAccount thirdAccount) {
        String sysUserId = thirdAccount.getSysUserId();
        if (oConvertUtils.isNotEmpty(sysUserId)) {
            SysUser sysUser = userMapper.selectById(sysUserId);
            sysUser.setAvatar(thirdAccount.getAvatar());
            sysUser.setRealname(thirdAccount.getRealname());
//            sysUser.setUsername(thirdAccount.getRealname());
            try {
                sysUser.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(thirdAccount.getBirthday()));
            }catch (Exception e){

            }
            sysUser.setPhone(thirdAccount.getPhone());
            this.userMapper.updateById(sysUser);
            return sysUser;
        } else {
            return sysThirdAccountService.createUser(thirdAccount);
        }
    }
}
